﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Linq;
using AcctrueWMS.Foundation.WebControls;
using AcctrueWMS.Foundation.Render;
using System.IO;
using AcctrueWMS.Foundation.DAL;
using AcctrueWMS.Foundation.Common;
using AcctrueWMS.Foundation.Util;
using System.Data;
using AcctrueWMS.Foundation.Web;
using System.Web;
using System.Collections;
using System.Web.Caching;
using System.Configuration;

namespace AcctrueWMS.Foundation.Data
{
    public class DataModelContext : IDataModelContext
    {
        private IDBOperator dboperator;

        public DataModelContext()
        {
            dboperator = DBFactory.CreateDBOperator();
            ///默认Context的路径为ModelFile路径
            //这个应该由RunTime初始化，在Context里面调用Runtime是不对的
            //FilePath = Runtime.ModelFilePath;
        }
        //public int ExecuteCommand(string cmdText)
        //{
        //    return WMSqlExcuter.ExecuteNonQuery(cmdText);//helper.ExecuteNonQuery(cmdText);
        //}
        public string FilePath
        {
            get;
            set;
        }
        public string ApplicationPath
        {
            get;
            set;
        }

        public string CommmonServiceUrl
        {
            get;
            set;
        }
        /// <summary>
        /// 页面呈现模式。0，查看；1，新增；2，修改。
        /// </summary>
        public int RenderMode
        {
            get
            {
                if (string.IsNullOrEmpty(HttpContext.Current.Request.QueryString["opt"])) return 0;
                return Convert.ToInt32(HttpContext.Current.Request.QueryString["opt"]);
            }
        }
        public DataModel ExecuteDataModel(string cmdText)
        {
            DataTable dt = WMSqlExcuter.ExecuteDataTable(cmdText);//helper.ExecuteDataTable(cmdText);
            DataModel model = new DataModel(Runtime.Context, "");
            ///加载datamode的结构
            FillModel(model);
            if (dt != null)
            {
                model.FromDataTable(dt);
            }
            return model;
        }
        /// <summary>
        /// 在DataModel文件夹下生成XML文件
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public XmlDocument GenerateModelXml(DataModel model)
        {
            XmlDataModelGenerator modelGenerator = new XmlDataModelGenerator();
            return (XmlDocument)modelGenerator.Generate(model);
        }
        /// <summary>
        /// 生成keyValue值
        /// </summary>
        /// <param name="model"></param>
        /// <returns>返回KeyValue值,格式为:[key1=value1,key2=value2]</returns>
        public string RenderKeyValue(DataModel model)
        {
            StringBuilder sb = new StringBuilder();
            if (model.KeyColumnName.Length > 0)
            {
                string[] keyNames = model.KeyColumnName.Split(',');
                for (int i = 0; i < keyNames.Length; i++)
                {
                    sb.Append(keyNames[i] + "=" + model[keyNames[i]].Value + "*");
                }
                if (sb.ToString().EndsWith("*"))
                    sb.Remove(sb.Length - 1, 1);
            }
            return sb.ToString();
        }
        /// <summary>
        /// 呈现控件
        /// </summary>
        /// <param name="cell"></param>
        /// <returns></returns>
        public string RenderCell(DataModelCell cell)
        {
            return RenderCell(cell, string.Empty);
        }
        /// <summary>
        /// 得到一个单元的值，适用于真实列和虚拟列
        /// </summary>
        /// <param name="cell"></param>
        public object GetCellValue(DataModelCell cell, DataRow row)
        {
            //转换虚拟列
            if (cell.Column.physicalType == "virtual")
            {
                cell.Column.Data = ReplaceTokenWithValue(cell.Column.Data, cell);

                object obj = CommandExprFactory.Eval(cell.Column.Data, this);
                if (obj is DataTable)
                {
                    DataTable retTable = obj as DataTable;
                    if (retTable.Rows.Count > 0)
                        return retTable.Rows[0][0].ToString();
                }
                else if (obj is string)
                    return obj.ToString();
                else if (obj != null)
                    return obj.ToString();
            }
            else if (row != null)
            {
                return row[cell.Column.Name];
            }
            return string.Empty;
        }
        /// <summary>
        /// 根据条件生成控件,如果是虚拟列,则直接生成控件;如果不是,则从数据库中获取相应的值并填充
        /// </summary>
        /// <param name="cell"></param>
        /// <param name="expr"></param>
        /// <returns></returns>
        public string RenderCell(DataModelCell cell, string expr)
        {
            expr = GetRealValueOfExpr(expr);

            string displayType = cell.Column.DisplayType;
            switch (RenderMode)
            {
                case 1:
                case 2:
                    break;
                case 0:
                case 3:
                    displayType = string.Empty;
                    break;
            }

            AccControl cellControl = GenerateContorl(displayType, cell.Column);
            cellControl.Enabled = cell.Column.Enable;
            cellControl.Musted = cell.Column.Musted;
            cellControl.ID = cell.Model.Name + "$" + cell.Column.Name + "$" + cell.RowIndex;
            cellControl.Name = cell.Model.Name + "$" + cell.Column.Name + "$" + cell.RowIndex;
            cellControl.DataType = cell.Column.ColumnType.Name;//control 的 控件 数据类型
            cellControl.Title = cell.Column.DisplayName;//设置控件title   
            cellControl.Length = cell.Column.Length;
            cellControl.Format = cell.Column.Format;
            //cellControl.OptType = this.RenderMode;  //根据页面呈现样式 呈现控件模式 1，新增；2，修改。
            //虚拟列采用表达式计算结果                

            if (!string.IsNullOrEmpty(cell.Column.ValidPattern))
                cellControl.ValidExpression = cell.Column.ValidPattern;
            if (!string.IsNullOrEmpty(cell.Column.Tip))
                cellControl.Tip = cell.Column.Tip;

            cellControl.Visible = cell.Column.Visible;
            ///生成默认值
            if (!string.IsNullOrEmpty(cell.Column.Default))
            {
                StringWriter sw = new StringWriter();
                this.Render.Render(cell.Column.Default, sw);
                cellControl.DefaultValue = sw.ToString();
            }
            if (!string.IsNullOrEmpty(cell.Column.Url))
                cellControl.Url = cell.Column.Url;
            if (!string.IsNullOrEmpty(cell.Column.Style))
                cellControl.Style = cell.Column.Style;

            if (cellControl is AccFocusedTextBox)
            {
                (cellControl as AccFocusedTextBox).DataExpression = cell.Column.Data;
                (cellControl as AccFocusedTextBox).Url = CommmonServiceUrl;
            }
            else if (!string.IsNullOrEmpty(cell.Column.Data)
                && cell.Column.physicalType != "virtual")
                cellControl.DataSource = CommandExprFactory.Eval(cell.Column.Data, this);

            Dictionary<string, string> nvpair = GetDefinationFromExpr(expr);
            //格式信息需要使用cell的真实值，故需在此处分析
            if (nvpair.ContainsKey("format"))
            {
                cell.Column.Format = nvpair["format"];
                nvpair.Remove("format");
                cellControl.Format = cell.Column.Format;

            }
            //string.Format("#0.00", "2342334.234");
            if (cell.Column.ColumnType.Name == "Decimal" && !string.IsNullOrEmpty(cell.Value==null?string.Empty:cell.Value.ToString()))
            {
                
                cellControl.SelectedValue = string.Format("{0:" + cell.Column.Format + "}", Convert.ToDecimal(cell.Value));
           }
            else
            {
                cellControl.SelectedValue = string.Format("{0:" + cell.Column.Format + "}", cell.Value);
            }
            

            return RenderControlByExpr(cellControl, nvpair);
        }
        /// <summary>
        /// Render表达式中可能包含vtl语法，首先得到这些值
        /// </summary>
        /// <param name="expr"></param>
        /// <returns></returns>
        private string GetRealValueOfExpr(string expr)
        {
            StringWriter sw = new StringWriter();
            Render.Render(expr, sw);
            return sw.ToString();
        }

        /// <summary>
        /// 从DataTable中分析相应数据
        /// </summary>
        /// <param name="dc"></param>
        /// <param name="row"></param>
        /// <returns></returns>
        private string ReplaceTokenWithValue(string expr, DataModelCell cell)
        {
            try
            {
                //分析匹配的可能参数，并进行替换。列参数以#开头
                Regex colname_reg = new Regex(@"\#{(?<colname>[\w|\d]+)}\s*");
                foreach (Match m in colname_reg.Matches(expr))
                {
                    string colName = m.Groups["colname"].Value;
                    if (cell.Model.Columns.ContainsKey(colName))
                    {
                        expr = expr.Replace(m.Value, cell.Model.ItemArray[colName].Value.ToString());
                    }
                }
                return expr;
            }
            catch
            {
                return string.Empty;
            }
        }
        /// <summary>
        /// 复制Control
        /// </summary>
        /// <param name="target"></param>
        /// <param name="source"></param>
        private void CopyControl(AccControl target, AccControl source)
        {
            target.DataSource = source.DataSource;
            target.DefaultValue = source.DefaultValue;
            target.Description = source.Description;
            target.Enabled = source.Enabled;
            target.ID = source.ID;
            target.Musted = source.Musted;
            target.Name = source.Name;
            target.SelectedValue = source.SelectedValue;
            target.Style = source.Style;
            target.Url = source.Url;
            target.ValidExpression = source.ValidExpression;
            target.Visible = source.Visible;
            target.Format = source.Format;
            if (target is AccFocusedTextBox && source is AccFocusedTextBox)
            {
                (target as AccFocusedTextBox).DataExpression = (source as AccFocusedTextBox).DataExpression;
            }
        }

        private string RenderControlByExpr(AccControl control, Dictionary<string, string> nvpair)
        {
            if (nvpair.ContainsKey("displaytype"))
            {
                AccControl newcontrol = GenerateContorl(nvpair["displaytype"]);
                CopyControl(newcontrol, control);
                control = newcontrol;
            }
            if (nvpair.ContainsKey("data"))
            {
                string dataexpr = nvpair["data"];
                if (control is AccFocusedTextBox)
                {
                    (control as AccFocusedTextBox).Url = CommmonServiceUrl;
                    (control as AccFocusedTextBox).DataExpression = dataexpr;
                }
                else
                    control.DataSource = CommandExprFactory.Eval(dataexpr, this);
                nvpair.Remove("data");
            }
            if (nvpair.ContainsKey("enabled"))
            {
                bool enabled = Convert.ToBoolean(nvpair["enabled"]);
                control.Enabled = enabled;
                nvpair.Remove("enabled");
            }

            if (nvpair.ContainsKey("length"))
            {
                string length = nvpair["length"];
                control.Length = length;
                nvpair.Remove("length");
            }

            if (nvpair.ContainsKey("musted"))
            {
                bool musted = Convert.ToBoolean(nvpair["musted"]);
                control.Musted = musted;
                nvpair.Remove("musted");

            }
            if (nvpair.ContainsKey("id"))
            {
                control.ID = nvpair["id"];
                control.Name = nvpair["id"];
                nvpair.Remove("id");
            }
            if (nvpair.ContainsKey("name"))
            {
                control.Name = nvpair["name"];
                nvpair.Remove("name");
            }
            if (nvpair.ContainsKey("validexpression"))
            {
                string validexpression = nvpair["validexpression"];
                control.ValidExpression = validexpression;
                nvpair.Remove("validexpression");
            }
            if (nvpair.ContainsKey("visible"))
            {
                bool visible = Convert.ToBoolean(nvpair["visible"]);
                control.Visible = visible;
                nvpair.Remove("visible");
            }
            ///生成默认值
            if (nvpair.ContainsKey("defaultvalue"))
            {
                StringWriter sw = new StringWriter();
                this.Render.Render(nvpair["defaultvalue"], sw);
                control.DefaultValue = sw.ToString();
                nvpair.Remove("defaultvalue");
            }
            if (nvpair.ContainsKey("value"))
            {
                StringWriter sw = new StringWriter();
                this.Render.Render(nvpair["value"], sw);
                control.SelectedValue = sw.ToString();
                nvpair.Remove("value");
            }
            if (nvpair.ContainsKey("url"))
            {
                control.Url = nvpair["url"];
                nvpair.Remove("url");
            }
            if (nvpair.ContainsKey("style"))
            {
                control.Style = nvpair["style"];
                nvpair.Remove("style");
            }
            if (control is AccFocusedTextBox)
            {
                if (nvpair.ContainsKey("dataexpression"))
                {
                    (control as AccFocusedTextBox).DataExpression = nvpair["dataexpression"];
                    nvpair.Remove("dataexpression");
                }
                //showvalue和checkexists是displayType的扩展属性，不应包含在nvpair中，考虑兼容型，咱包括
                if (nvpair.ContainsKey("showvalue"))
                {
                    (control as AccFocusedTextBox).ShowValue = bool.Parse(nvpair["showvalue"]);
                    nvpair.Remove("showvalue");
                }
                // 数据验证配置 在Render(.....) 中
                if (nvpair.ContainsKey("checkexists"))
                {
                    (control as AccFocusedTextBox).CheckExists = nvpair["checkexists"];
                }
            }
            if (nvpair.Count > 0)
            {
                foreach (KeyValuePair<string, string> kev in nvpair)
                {
                    control.Property += " " + kev.Key + "='" + kev.Value + "' ";
                }
            }
            //如果所选值不为空，则填充Text属性
            if (control is AccFocusedTextBox && !string.IsNullOrEmpty(control.SelectedValue))
            {
                //将占位符替换为实际值
                string dataExpr = (control as AccFocusedTextBox).DataExpression.Replace("{value}", control.SelectedValue);
                DataRow[] rows = (CommandExprFactory.Eval(dataExpr, this) as DataTable).Select("key='" + control.SelectedValue + "'");
                if (rows.Length > 0)
                {
                    control.Text = rows[0]["value"].ToString();
                }
            }
            return control.Render();
        }
        /// <summary>
        /// 根据表达式覆盖控件的各项属性,如果存在非常规属性,则将非常规属性直接添加到控件的属性中
        /// </summary>
        /// <param name="control"></param>
        /// <param name="expr"></param>
        /// <returns></returns>
        private string RenderControlByExpr(AccControl control, string expr)
        {
            Dictionary<string, string> nvpair = GetDefinationFromExpr(expr);
            return RenderControlByExpr(control, nvpair);
        }
        /// <summary>
        /// 从字符串中分析属性信息
        /// </summary>
        /// <param name="expr"></param>
        /// <returns></returns>
        private Dictionary<string, string> GetDefinationFromExpr(string expr)
        {
            Dictionary<string, string> nvpair = new Dictionary<string, string>();
            foreach (Match m in ctl_render_reg.Matches(expr))
            {
                string name = m.Groups["name"].Value.ToLower();
                string value = m.Groups["value"].Value;
                nvpair.Add(name, value);
            }
            return nvpair;
        }
        /// <summary>
        /// 分析字符串，字符串格式与DataModel列定义值类似，形如：displayType=tree;data=wmsql(sth);
        /// </summary>
        /// <param name="expr"></param>
        /// <returns></returns>
        public string CreateControl(string expr)
        {
            Dictionary<string, string> nvpair = GetDefinationFromExpr(expr);
            if (nvpair.Count == 0) return string.Empty;

            string displayType = nvpair["displaytype"];
            AccControl control = GenerateContorl(displayType);
            return RenderControlByExpr(control, expr);
        }


        private static Regex ctl_render_reg = new Regex(@"(?<name>[\w|\d]+)\s*=\s*(?<value>.*?);");


        private static Regex ctl_arr_reg = new Regex(@"(?<name>[\w|\d]+)\s*=\s*(?<value>.*)");
        /// <summary>
        /// 根据控件类型生成不同控件
        /// </summary>
        /// <param name="controlType"></param>
        /// <returns></returns>
        private AccControl GenerateContorl(string controlType, DataModelColumn column)
        {
            AccControl accControl = null;
            Dictionary<string, string> attr = new Dictionary<string, string>();
            foreach (Match m in ctl_arr_reg.Matches(controlType))
            {
                string arrKey = m.Groups["name"].Value.ToLower();
                if (!attr.ContainsKey(arrKey))
                    attr[arrKey] = m.Groups["value"].Value.ToLower();
            }
            switch (controlType.Split(',')[0].ToLower())
            {
                case "radio":
                    accControl = new AccRadioButton();
                    // accControl.DisplayMember
                    break;
                case "textbox":
                    accControl = new AccTextBox();
                    break;
                case "checkbox":
                    accControl = new AccCheckBox();
                    break;
                case "text":
                    accControl = new AccText();
                    break;
                case "focusedtextbox":
                    accControl = new AccFocusedTextBox();
                    if (attr.ContainsKey("showvalue"))
                        (accControl as AccFocusedTextBox).ShowValue = bool.Parse(attr["showvalue"]);
                    if (attr.ContainsKey("checkexists"))
                        (accControl as AccFocusedTextBox).CheckExists = attr["checkexists"].ToLower();
                    else
                        (accControl as AccFocusedTextBox).CheckExists = AccFocusedTextBox.NoCheck;
                    break;
                case "calendar":
                    accControl = new AccCalendar();
                    break;
                case "dropdownlist":
                    accControl = new AccDropDownList();
                    break;
                case "tree":
                    AccTree tree = new AccTree();
                    if (attr.ContainsKey("checkable"))
                        tree.Checkable = bool.Parse(attr["checkable"]);
                    accControl = tree;
                    break;
                case "textarea":
                    accControl = new AccTextArea();
                    break;
                case "label":
                    accControl = new AccLabel();
                    break;
                case "password":
                    accControl = new AccPassword();
                    break;
                case "fileupload":
                    accControl = new AccFileUpload();
                    break;
                default:
                    accControl = new AccControl();
                    break;
            }
            accControl.Context = this;
            return accControl;
        }
        /// <summary>
        /// 根据控件类型生成不同控件
        /// </summary>
        /// <param name="controlType"></param>
        /// <returns></returns>
        private AccControl GenerateContorl(string controlType)
        {
            return GenerateContorl(controlType, null);
        }
        /// <summary>
        /// 呈现列,如果可排序,则在生成的html中添加sort属性
        /// </summary>
        /// <param name="column">数据列</param>
        /// <returns>生成排序连接字符串</returns>
        public string RenderColumn(DataModelColumn column)
        {
            if (this.RenderMode == 1)
            {
                return string.Format("<span id=\"col_{0}\">{0}</span>",
                        column.DisplayName);
            }
            else
            {
                if (column.Sortable)
                {
                    HttpRequest request = HttpContext.Current.Request;
                    bool desc = false;

                    string orderBy = column.Name;  //默认按照字段排序
                    if (!string.IsNullOrEmpty(column.sortBy.Trim()))
                    {
                        orderBy = column.sortBy;
                    }

                    if (!string.IsNullOrEmpty(request.QueryString["orderby"]))
                    {
                        //查询字符串中的排序优先级高于配置文件，首先查找查询字符串中相应的排序条件，以判断正反序
                        if (request.QueryString["orderby"].IndexOf(orderBy + " asc") > -1)
                            desc = false;
                        else if (request.QueryString["orderby"].IndexOf(orderBy + " desc") > -1)
                            desc = true;
                    }
                    else if (column.Sort == "asc")
                        desc = false;
                    else
                        desc = true;

                    string innerText = string.Format("<span id=\"col_{0}\">{0}</span>",
                        column.DisplayName);
                    if (column.Sortable)
                    {

                        if (desc)
                        {
                            innerText += string.Format("<img style=\"cursor:hand\" absalign=\"middle\"  onclick=\"wmsCommon.sort('{0}','{0} asc');\" border=\"0\" src=\"{1}\"/>",
                            orderBy, this.ApplicationPath + "/res/images/accList_down.gif");
                        }
                        else
                        {
                            innerText += string.Format("<img style=\"cursor:hand\" onclick=\"wmsCommon.sort('{0}','{0} desc');\" border=\"0\" src=\"{1}\"/>",
                            orderBy, this.ApplicationPath + "/res/images/accList_up.gif");
                        }
                    }
                    return innerText;
                }
                else
                {
                    return string.Format("<span id=\"col_{0}\">{0}</span>",
                        column.DisplayName);
                }
            }
        }
        public ICache Cache
        {
            get
            {
                return Runtime.Cache;
            }
        }
        /// <summary>
        /// 填充数据实体的结构,填充时,加载DataModel的基本结构 列 关联信息和事件信息
        /// </summary>
        /// <param name="model">数据模型</param>
        public void FillModel(DataModel model)
        {
            Dictionary<string, Type> dirType = Web.TypeConverter.Converter.DirType;
            //加载DataModel属性
            string fullpathName = string.Empty;
            string urlModelName = model.Name.Trim();
            if (!urlModelName.Contains(".xml"))
                fullpathName = this.FilePath + "\\" + urlModelName + ".xml";
            else
                fullpathName = this.FilePath + "\\" + urlModelName;
            if (!File.Exists(fullpathName))
            {
                return;
            }

            XDocument xd = null;

            #region 缓存 XDocument

            //bool isCaching = bool.Parse(ConfigurationManager.AppSettings["IsCaching"]);
            //string key = "model_" + model.Name;
            //if (this.Cache[key] == null || isCaching == false)
            //{
              xd = XDocument.Load(fullpathName);

            //    if (isCaching == true)
            //        this.Cache[key] = xd;
            //}
            //else
            //{
            //    xd = this.Cache[key] as XDocument;
            //}

            #endregion

            #region 加载Model基本信息
            model.Name = xd.Root.Attribute("name") == null ? string.Empty : xd.Root.Attribute("name").Value;
            model.GeneratingCommand = xd.Root.Attribute("generatingCommand") == null ? string.Empty : xd.Root.Attribute("generatingCommand").Value;
            model.DisplayName = xd.Root.Attribute("displayName") == null ? string.Empty : xd.Root.Attribute("displayName").Value;
            model.physicalName = xd.Root.Attribute("physicalName") == null ? string.Empty : xd.Root.Attribute("physicalName").Value;         
            model.KeyColumnName = xd.Root.Attribute("keyColumnName") == null ? string.Empty : xd.Root.Attribute("keyColumnName").Value;
            //wbs 字段配置
            model.WbsCodeColumn = xd.Root.Attribute("wbsCodeColumnName") == null ? string.Empty : xd.Root.Attribute("wbsCodeColumnName").Value;
            //wbs格式配置
            model.WbsCodeGenType = xd.Root.Attribute("wbsCodeGenType") == null ? string.Empty : xd.Root.Attribute("wbsCodeGenType").Value;
            //是否分页
            model.ifPaging = xd.Root.Attribute("ifPaging") == null ? string.Empty : xd.Root.Attribute("ifPaging").Value;
            //是否改变底层的con取数
            model.ifChangeCon = xd.Root.Attribute("ifChangeCon") == null ? string.Empty : xd.Root.Attribute("ifChangeCon").Value;
            #endregion
            //Model.Columns
            #region 加载DataModel对应的列信息
            IEnumerable<XElement> columns = xd.Root.Element("Columns").Elements();
            foreach (XElement column in columns)
            {
                DataModelColumn modelColumn = new DataModelColumn();
                modelColumn.Model = model;
                modelColumn.Name = column.Attribute("name") == null ? string.Empty : column.Attribute("name").Value;
                modelColumn.DisplayName = column.Attribute("displayName") == null ? string.Empty : column.Attribute("displayName").Value;
                modelColumn.Length = column.Attribute("length") == null ? string.Empty : column.Attribute("length").Value;
                modelColumn.Width = column.Attribute("width") == null ? string.Empty : column.Attribute("width").Value;
                modelColumn.Height = column.Attribute("height") == null ? string.Empty : column.Attribute("height").Value;
                modelColumn.ColumnType = dirType[column.Attribute("columnType").Value];
                modelColumn.Nullable = column.Attribute("nullable") == null ? true : Convert.ToBoolean(column.Attribute("nullable").Value);
                modelColumn.DisplayType = (column.Attribute("displayType") == null || string.IsNullOrEmpty(column.Attribute("displayType").Value)) ? "TextBox".ToLower() : column.Attribute("displayType").Value;
                modelColumn.physicalType = column.Attribute("physicalType") == null ? string.Empty : column.Attribute("physicalType").Value.ToLower();
                modelColumn.Visible = column.Attribute("visible") == null ? true : Convert.ToBoolean(column.Attribute("visible").Value);
                modelColumn.Enable = column.Attribute("enable") == null ? true : Convert.ToBoolean(column.Attribute("enable").Value);
                modelColumn.Sortable = column.Attribute("sortable") == null ? false : Convert.ToBoolean(column.Attribute("sortable").Value);
                modelColumn.Sort = column.Attribute("sort") == null ? string.Empty : column.Attribute("sort").Value;
                modelColumn.Searchable = column.Attribute("searchable") == null ? false : Convert.ToBoolean(column.Attribute("searchable").Value);
                modelColumn.Data = column.Attribute("data") == null ? string.Empty : column.Attribute("data").Value;
                modelColumn.Default = column.Attribute("defaultValue") == null ? string.Empty : column.Attribute("defaultValue").Value;
                modelColumn.ValidPattern = column.Attribute("validPattern") == null ? string.Empty : column.Attribute("validPattern").Value;
                modelColumn.Tip = column.Attribute("tip") == null ? string.Empty : column.Attribute("tip").Value;//校验未通过提示语
                modelColumn.Url = column.Attribute("Url") == null ? string.Empty : column.Attribute("Url").Value;
                modelColumn.Style = column.Attribute("style") == null ? string.Empty : column.Attribute("style").Value;
                modelColumn.QueryType = column.Attribute("queryType") == null ? string.Empty : column.Attribute("queryType").Value;
                modelColumn.Format = column.Attribute("format") == null ? string.Empty : column.Attribute("format").Value;
                modelColumn.sortBy = column.Attribute("sortBy") == null ? string.Empty : column.Attribute("sortBy").Value;

                modelColumn.DataVolideExpr = column.Attribute("DataVolideExpr") == null ? string.Empty : column.Attribute("DataVolideExpr").Value;//数据验证表达式
                

                //DisplayMember和ValueMember不在此处定义，需要数据源的，默认都是用key,value,text
                //modelColumn.DisplayMember = column.Attribute("displayMember") == null ? string.Empty : column.Attribute("displayMember").Value;
                //modelColumn.ValueMember = column.Attribute("valueMember") == null ? string.Empty : column.Attribute("valueMember").Value;
                ///流水号/生成方式,如果标记该属性,则可自动生成流水号
                modelColumn.SequenceNoGenType = column.Attribute("sequenceNoGenType") == null ? string.Empty : column.Attribute("sequenceNoGenType").Value;
                string musted = column.Attribute("musted") == null ? string.Empty : column.Attribute("musted").Value;
                if (musted.Length > 0)
                    modelColumn.Musted = Convert.ToBoolean(musted);
                else modelColumn.Musted = false;
                model.Columns.Add(modelColumn);
            }

            //新增ROWNUM列   create by tianp
            DataModelColumn modelRowNumColumn = new DataModelColumn();
            modelRowNumColumn.Model = model;
            modelRowNumColumn.Name = "ROWNUM";
            modelRowNumColumn.DisplayName = "序号";
            modelRowNumColumn.Sortable = false;
            modelRowNumColumn.SequenceNoGenType = string.Empty;
            modelRowNumColumn.physicalType = "virtual";
            modelRowNumColumn.ColumnType = string.Empty.GetType();

            model.Columns.Add(modelRowNumColumn);
            //end

            #endregion

            //加载Model.Childs和Model.Brothers
            #region 加载DataModel关联,关联包括Brothers和Childs
            IEnumerable<XElement> relationsNode = xd.Root.Element("Relations") == null ? null : xd.Root.Element("Relations").Elements();
            model.Childs = new DataModelCollection(model);

            if (relationsNode != null)
            {
                foreach (XElement relationNode in relationsNode)
                {
                    DataModelRelation relation = new DataModelRelation();
                    string name = relationNode.Attribute("Model").Value;
                    string relationType = relationNode.Attribute("relationType") == null ? "child" : relationNode.Attribute("relationType").Value;

                    //string childModelPath = fullpathName.Replace(fullpathName.Substring(fullpathName.LastIndexOf(@"\")), @"\" + name + ".xml");
                    // this.FilePath = childModelPath;

                    model.Relations.Add(relation);
                    relation.From = model;
                    relation.To = new DataModel(this, name);
                    relation.RelationExpression = relationNode.Attribute("expression").Value;
                    relation.RelationType = relationType == "child" ? RelationType.Child : RelationType.Brother;
                    if (relation.RelationType == RelationType.Child)
                        model.Childs.Add(relation.To);
                    else
                        model.Brothers.Add(relation.To);
                }
            }
            #endregion

            #region 加载DataModel事件信息
            IEnumerable<XElement> eventColumns = xd.Root.Element("events") == null ? null : xd.Root.Element("events").Elements();
            model.DataModelEvents = new System.Collections.ObjectModel.Collection<DataModelEventInfo>();
            if (eventColumns != null)
            {
                foreach (XElement column in eventColumns)
                {
                    DataModelEventInfo info = new DataModelEventInfo();
                    info.EventName = column.Attribute("name") == null ? string.Empty : column.Attribute("name").Value;
                    info.EventExpr = column.Attribute("method") == null ? string.Empty : column.Attribute("method").Value;

                    if (!model.DataModelEvents.Contains(info))
                    {
                        model.DataModelEvents.Add(info);
                    }
                }
            }

            #endregion
        }

        public DataModel Select(DataModel model, string condition, string orderBy)
        {
            return Select(model, condition, orderBy, -1, -1);
        }

        public DataModel Select(DataModel model, string condition)
        {
            return Select(model, condition, -1, -1);
        }
        public DataModel Select(DataModel model, string condition, bool withRelation)
        {
            return Select(model, condition, null, -1, -1, withRelation);
        }
        public DataModel Select(DataModel model, string condition, int startIndex, int endIndex)
        {
            return Select(model, condition, null, startIndex, endIndex);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="modelName"></param>
        /// <param name="dt"></param>
        /// <param name="dtBrothers"></param>
        /// <param name="listChilds"></param>
        /// <returns></returns>
        public DataModel FillDataModelFromDataTable(string modelName, DataTable dt)
        {
            DataModel model = new DataModel(this, modelName);
            model.FromDataTable(dt);

            return model;
        }
        public void FillBrothers(DataModel model, Dictionary<string, DataTable> dtBrothers)
        {
            for (int i = 0; i < model.Brothers.Count; i++)
            {
                if (dtBrothers[model.Brothers[i].Name] != null)
                {
                    model.Brothers[i].FromDataTable(dtBrothers[model.Brothers[i].Name]);
                }
            }
        }

        public void FillChilds(DataModel model, Dictionary<string, DataTable> dtChilds)
        {
            for (int i = 0; i < model.Brothers.Count; i++)
            {
                if (dtChilds[model.Brothers[i].Name] != null)
                {
                    model.Brothers[i].FromDataTable(dtChilds[model.Brothers[i].Name]);
                }
            }
        }
        public DataModel Select(DataModel model, string condition, string orderBy, int startIndex, int endIndex)
        {
            bool withRelation = false;
            if (this.RenderMode != 0)
                withRelation = true;
            return Select(model, condition, orderBy, startIndex, endIndex, withRelation);
        }
        public DataModel Select(DataModel model, string condition, string orderBy, int startIndex, int endIndex, bool withRelation)
        {
            //是否存在生成语句
            bool hasCommand = true;
            string cmdText = string.Empty;
            //查询语句
            string generatingCommand = string.Empty;
            //数据总数查询语句
            string totalCommand = string.Empty;
            CommandExpressionTypeEnum commandType = CommandExpressionTypeEnum.Text;
            string tableName = string.IsNullOrEmpty(model.physicalName) ? model.Name : model.physicalName.ToString();
            ///如果Model使用XML中的查询条件
            if (!string.IsNullOrEmpty(model.GeneratingCommand))
            {
                hasCommand = true;
                generatingCommand = model.GeneratingCommand;
                commandType = CommandExprFactory.DetectType(generatingCommand, out cmdText);
                if (hasCommand && commandType == CommandExpressionTypeEnum.WMSQL )
                {
                    string where = null;
                    if (!string.IsNullOrEmpty(condition))
                    {
                        condition = condition.Trim();
                        where = " where " + condition;
                    }
                    string orderByStr = null;
                    if (!string.IsNullOrEmpty(orderBy))
                        orderByStr = " order by " + orderBy;
                    string range = null;
                    if ((startIndex == -1 || endIndex == -1)&& model.ifPaging.ToLower()!="false")
                        range = null;
                    else
                    {
                        if (string.IsNullOrEmpty(orderBy))
                        {
                            range = string.Format(" range {0},{1},{2}", startIndex, endIndex, model.KeyColumnName);
                        }
                        else
                        {
                            range = string.Format(" range {0},{1},{2}", startIndex, endIndex, orderBy);
                        }
                    }
                    generatingCommand = string.Format("wmsql(select * from ({0})  {1}  {2} {3} {4})", cmdText, tableName, where, orderByStr, range);
                    totalCommand = string.Format("wmsql(select count(*) from ({0}) {1}  {2})", cmdText, tableName, where);
                }
            }
            else
            {
                hasCommand = false;
       
                generatingCommand = string.Format("select * from {0} ", tableName);
                totalCommand = string.Format("wmsql(select count(*) from {0}", tableName);
                if (!string.IsNullOrEmpty(condition))
                {
                    ///防止condition是空格组成的串
                    if (!string.IsNullOrEmpty(condition.Trim()))
                    {
                        generatingCommand += " where " + condition;
                        totalCommand += " where " + condition;
                    }
                }
                totalCommand += ")";

                if (!string.IsNullOrEmpty(orderBy))
                    generatingCommand += " order by " + orderBy;

                if (startIndex != -1 && endIndex != -1)
                {
                    //如果不存在排序条件，则使用主键列
                    if (string.IsNullOrEmpty(orderBy))
                        generatingCommand += string.Format(" range {0},{1},{2}", startIndex, endIndex, model.KeyColumnName);
                    else
                        generatingCommand += string.Format(" range {0},{1}", startIndex, endIndex);
                }
                generatingCommand = string.Format("wmsql({0})", generatingCommand);
            }

            //generatingCommand = Render.Render(generatingCommand);
            DataTable dt = CommandExprFactory.Eval(generatingCommand, this) as DataTable;
            DataTable resultTable = dt;
            //如果存在生成语句，则从其查询的DataTable中分页查询
            if (hasCommand && commandType == CommandExpressionTypeEnum.Sys)
            {
                DataView view = dt.DefaultView;
                //create by tianp   不在底层做数据过滤  做特殊处理
                if (!string.IsNullOrEmpty(model.ifChangeCon) && model.ifChangeCon.ToLower() == "false")
                    condition = "1=1";
                // end 

                view.RowFilter = GetFilterForDataTable(condition);
                view.Sort = orderBy;
                //如果不存在分页
                if ((startIndex == -1 || endIndex == -1)  && model.ifPaging.ToLower()!="false")
                    resultTable = view.ToTable();
                else
                {
                    //克隆表，并选取分页限制的行
                    resultTable = dt.Clone();
                    for (int i = startIndex - 1; i < view.Count && i < endIndex; i++)
                    {
                        DataRow row = resultTable.NewRow();
                        object[] array = new object[row.ItemArray.Length];
                        view[i].Row.ItemArray.CopyTo(array, 0);
                        row.ItemArray = array;
                        resultTable.Rows.Add(row);
                    }
                }
            }
            //如果总数查询语句不为空，则查询总数
            if (!string.IsNullOrEmpty(totalCommand))
            {
                DataTable totalTable = (DataTable)CommandExprFactory.Eval(totalCommand, this);
                model.TotalCount = (int)totalTable.Rows[0][0];
            }
            else if (dt != null)
            {
                model.TotalCount = dt.Rows.Count;
            }
            model.FromDataTable(resultTable);

            if (withRelation)
                FillModelWithChildAndBrother(model, condition);
            return model;
        }
        //去除条件中的表名，RowFilter不支持表名条件
        private string GetFilterForDataTable(string condition)
        {
            Regex regex = new Regex(@"(?<table>[\w|\d]+)\.(?<col>[\w|\d]+)");
            return regex.Replace(condition, new MatchEvaluator(RemoveTableName));
        }
        private string RemoveTableName(Match m)
        {
            return m.Groups["col"].Value;
        }
        /// <summary>
        /// 根据条件填充DataModel,包括Child和Brother
        /// </summary>
        /// <param name="model"></param>
        /// <param name="condition"></param>
        private void FillModelWithChildAndBrother(DataModel model, string condition)
        {
            foreach (DataModelRelation relation in model.Relations)
            {
                foreach (DataModel row in model.Rows)
                {
                    if (relation.RelationType == RelationType.Child)
                        this.Select(row.Childs[relation.To.Name], ParseRelationCondition(row, relation.To, relation));
                    else
                        this.Select(row.Brothers[relation.To.Name], ParseRelationCondition(row, relation.To, relation));
                }
            }
            //如果模型的行数大于0，则使用第一行的数据，这是为了简化模板的编写
            if (model.Rows.Count > 0)
            {
                model.Childs = model.Rows[0].Childs;
                model.Brothers = model.Rows[0].Brothers;
            }
        }
        //分析关系的正则表达式
        //private static Regex rel_reg = new Regex(@"(?<from>[\w|\d]+)\.(?<fromCol>[\w|\d]+)\s*(=|like)\s*(?<to>[\w|\d]+)\.(?<toCol>[\w|\d]+)");
        /// <summary>
        /// 得到关系对应的查询条件
        /// </summary>
        /// <param name="from">主模型，含有数据，是单条数据</param>
        /// <param name="to">子模型</param>
        /// <param name="relation">模型关系。关系中的模型仅含结构，不含数据</param>
        /// <returns></returns>
        private string ParseRelationCondition(DataModel from, DataModel to, DataModelRelation relation)
        {
            //如果主模型数据为空，则对应关系模型数据也应为空
            if (from.Rows.Count == 0)
                return "1!=1";
            else
            {
                string condition = relation.RelationExpression;
                Regex regex = new Regex(@"(?<model>[\w|\d]+)\.(?<column>[\w|\d]+)");
                string  tableName=string.IsNullOrEmpty(to.physicalName)?to.Name:to.physicalName;
                foreach (Match m in regex.Matches(relation.RelationExpression))
                {
                    if (m.Groups["model"].Value == from.Name)
                    {
                        condition = condition.Replace(m.Value,
                            "'" + DataHelper.CheckForNull(from.Rows[0][m.Groups["column"].Value].Value).ToString() + "'");
                    }
                }
                return condition.Replace(to.Name, tableName);
            }
        }

        /// <summary>
        ///功能： Range 查询
        /// </summary>
        /// <param name="model">数据模型</param>
        /// <param name="condition">条件</param>
        /// <param name="start">起始行数</param>
        /// <param name="end">截至行数</param>
        /// <returns>返回 查询结果</returns>
        public DataModel Range(DataModel model, string condition, int start, int end)
        {
            return Select(model, condition, start, end);
        }
        /// <summary>
        /// 功能：排序
        /// </summary>
        /// <param name="model">数据模型</param>
        /// <param name="orderBy">排序字段</param>
        /// <returns>返回 查询结果</returns>
        public DataModel Order(DataModel model, string orderBy)
        {
            return Select(model, null, orderBy);
        }
        /// <summary>
        ///  功能：查询单行记录
        /// </summary>
        /// <param name="model">数据模型</param>
        /// <param name="condition">条件</param>
        /// <returns>返回 查询结果</returns>
        public DataModel Single(DataModel model, string condition)
        {
            ///2011-5-24 操敏更改,返回单条记录时,其明细均为该单条记录下的明细
            DataModel rtnModel = Select(model, condition).Rows[0];
            FillModelWithChildAndBrother(rtnModel, condition);
            return rtnModel;

        }
        /// <summary>
        /// 通用的保存方法
        /// </summary>
        /// <param name="model"></param>
        /// <param name="state"></param>
        /// <returns>保存后返回主键表达式</returns>
        public string Save(DataModel model, string state)
        {
            TableModel[] tableModels = new TableModel[model.Childs.Count + model.Brothers.Count + 1];
            //为主表赋值
            TableModel tableModel = new TableModel();
            tableModel.DataTable = model.ToDataTable();
            tableModel.KeyName = model.KeyColumnName;
            tableModels[0] = tableModel;
            //从表  
            int childNum = 1;
            foreach (DataModelRelation relation in model.Relations)
            {
                TableModel tableChildModel = new TableModel();
                DataModel tempModel = relation.To;

                tableChildModel.DataTable = tempModel.ToDataTable();
                tableChildModel.KeyName = tempModel.KeyColumnName;
                string foreignName = relation.RelationExpression.Substring(relation.RelationExpression.LastIndexOf(".") + 1);
                tableChildModel.ForeignName = foreignName;
                tableModels[childNum] = tableChildModel;
                childNum++;
            }
            //获取修改的主表键       
            string returnValue = dboperator.SaveTables(tableModels, state);
            //保存之后返回主键值表达式
            return GetKeyNameValueExpress(tableModel.KeyName, returnValue);
            //string condition = string.Format(" 1=1 {0}  ", GetKeyNameValueExpress(tableModel.KeyName, returnValue, tableModels[0].DataTable.TableName.Trim()));
            //for (int rowIndex = model.Rows.Count - 1; rowIndex >= 0; rowIndex--)
            //{
            //    model.Rows.RemoveAt(rowIndex);
            //}
            //model = Select(model, condition);
            //return model;
        }

        //分析联合主键表达式
        /// <summary>
        /// 分析联合主键表达式
        /// </summary>
        /// <param name="keyColumnName"></param>
        /// <param name="keyColumnValues"></param>
        /// <returns>返回联合主键表达式,格式为key1=value1&key2=value2</returns>
        private string GetKeyNameValueExpress(string keyColumnName, string keyColumnValues)
        {
            string express = string.Empty;
            if (string.IsNullOrEmpty(keyColumnName) || string.IsNullOrEmpty(keyColumnValues)) return null;
            string[] arraykeyNames = keyColumnName.Split(',');
            string[] arrayKeyValues = keyColumnValues.Split(',');
            if (arraykeyNames.Length != arrayKeyValues.Length) return null;
            for (int i = 0; i < arraykeyNames.Length; i++)
            {
                express += string.Format("{0}={1}", arraykeyNames[i], arrayKeyValues[i]) + "*";
            }
            if (!string.IsNullOrEmpty(express))
            {
                express = express.Substring(0, express.Length - 1);
            }
            return express;
        }
        /// <summary>
        /// 删除方法发
        /// </summary>
        /// <param name="model"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public int Delete(DataModel model, string condition)
        {
            string tableName = string.IsNullOrEmpty(model.physicalName) ? model.Name : model.physicalName.ToString();
            return WMSqlExcuter.ExecuteRealNonQuery("delete from " + tableName + "   " + condition);
        }

        public DataModel Join(DataModel left, DataModel right, string condition)
        {
            throw new NotImplementedException();
        }

        public DataModelCell GetCell(DataModel model, int row, int col)
        {
            return model.Rows[row][col];
        }

        public DataModelCell GetCell(DataModel model, int row, string colName)
        {
            return model.Rows[row][colName];
        }

        public void SetCell(DataModel model, int row, int col, object value)
        {
            model.Rows[row][col].Value = value;
        }

        public void SetCell(DataModel model, int row, string colName, object value)
        {
            model.Rows[row][colName].Value = value;
        }

        IModelRender render;
        public IModelRender Render
        {
            get
            {
                if (render == null)
                    render = new VTLModelRender();
                return render;
            }
        }

        /// <summary>
        /// 呈现查询模块
        /// </summary>
        /// <param name="dataModelColumn"></param>
        /// <returns></returns>
        public string RenderAsQuery(DataModelColumn dataModelColumn)
        {
            return RenderAsQuery(dataModelColumn, string.Empty);
        }
        /// <summary>
        /// 生成查询控件
        /// </summary>
        /// <param name="column"></param>
        /// <param name="expr"></param>
        /// <returns></returns>
        public string RenderAsQuery(DataModelColumn column, string expr)
        {
            expr = GetRealValueOfExpr(expr);
            string query = HttpContext.Current.Request.QueryString["query"];

            //如果不是范围查询
            if (column.QueryType != "range")
            {
                AccControl cellControl = GenerateContorl(column.DisplayType, column);
                //cellControl.Enabled = column.Enable;
                cellControl.ID = column.Name;
                cellControl.Name = column.Name;
                cellControl.Title = column.DisplayName;
                cellControl.Format = column.Format;
                if (!string.IsNullOrEmpty(column.ValidPattern))
                    cellControl.ValidExpression = column.ValidPattern;
                if (!string.IsNullOrEmpty(column.Tip))
                    cellControl.Tip = column.Tip;
                cellControl.Visible = column.Visible;
                if (!string.IsNullOrEmpty(column.Url))
                    cellControl.Url = column.Url;

                if (!string.IsNullOrEmpty(column.Default))
                    cellControl.SelectedValue = GetRealValueOfExpr(column.Default);
                if (!string.IsNullOrEmpty(query))
                    cellControl.SelectedValue = ParseValueFromQuery(query, column);
                if (!string.IsNullOrEmpty(column.Data))
                {
                    if (cellControl is AccFocusedTextBox)
                    {
                        (cellControl as AccFocusedTextBox).DataExpression = column.Data;
                        cellControl.Url = CommmonServiceUrl;
                        cellControl.DataSource = CommandExprFactory.Eval(column.Data.Replace("{value}", cellControl.SelectedValue), this);
                    }
                    else
                    {
                        cellControl.DataSource = CommandExprFactory.Eval(column.Data, this);
                    }
                }
                return RenderControlByExpr(cellControl, expr);
            }
            else
            {
                AccControl cellControl1 = GenerateContorl(column.DisplayType, column);
                AccControl cellControl2 = GenerateContorl(column.DisplayType, column);
                //cellControl.Enabled = column.Enable;
                cellControl1.ID = column.Name + "$1";
                cellControl1.Name = column.Name + "$1";
                cellControl2.ID = column.Name + "$2";
                cellControl2.Name = column.Name + "$2";
                cellControl1.Format = column.Format;
                cellControl2.Format = column.Format;
                if (!string.IsNullOrEmpty(column.ValidPattern))
                {
                    cellControl1.ValidExpression = column.ValidPattern;
                    cellControl2.ValidExpression = column.ValidPattern;
                }
                cellControl1.Visible = column.Visible;
                cellControl2.Visible = column.Visible;
                if (!string.IsNullOrEmpty(column.Url))
                {
                    cellControl1.Url = column.Url;
                    cellControl2.Url = column.Url;
                }
                if (!string.IsNullOrEmpty(column.Data))
                {
                    if (cellControl1 is AccFocusedTextBox)
                    {
                        (cellControl1 as AccFocusedTextBox).DataExpression = column.Data;
                        cellControl1.Url = CommmonServiceUrl;
                        (cellControl2 as AccFocusedTextBox).DataExpression = column.Data;
                        cellControl2.Url = CommmonServiceUrl;
                    }
                    else
                    {
                        cellControl1.DataSource = CommandExprFactory.Eval(column.Data, this);
                        cellControl2.DataSource = CommandExprFactory.Eval(column.Data, this);
                    }
                }
                string[] defaultValues = null;
                //如果参数指定了默认值
                Dictionary<string, string> nvpair = GetDefinationFromExpr(expr);

                if (!string.IsNullOrEmpty(query))
                    defaultValues = ParseValueFromQuery(query, column).Split('|');
                else if (nvpair.ContainsKey("default"))
                    defaultValues = nvpair["default"].Split('|');
                else if (!string.IsNullOrEmpty(column.Default))
                    defaultValues = column.Default.Split('|');

                if (defaultValues != null && defaultValues.Length >= 2)
                {
                    cellControl1.SelectedValue = CommandExprFactory.Eval(defaultValues[0], this).ToString();
                    cellControl2.SelectedValue = CommandExprFactory.Eval(defaultValues[1], this).ToString();
                }
                //如果只按照一个条件来进行查询，同样需要绑定值
                else if (defaultValues != null && defaultValues.Length == 1 && !string.IsNullOrEmpty(query))
                {
                    if (query.IndexOf(">") > -1)
                    {
                        cellControl1.SelectedValue = CommandExprFactory.Eval(defaultValues[0], this).ToString();
                    }
                    else
                    {
                        cellControl2.SelectedValue = CommandExprFactory.Eval(defaultValues[0], this).ToString();
                    }
                }
                return string.Format("<nobr>{0} 到 {1}</nobr>", RenderControlByExpr(cellControl1, nvpair), RenderControlByExpr(cellControl2, nvpair));
            }
        }

        //从查询串中得到查询控件的值
        private string ParseValueFromQuery(string query, DataModelColumn column)
        {
            if (string.IsNullOrEmpty(query))
                return string.Empty;
            Regex regex = new Regex(@"(?<name>[\w|\d]+)(\s+like\s+|\s*=\s*|>=|<=)['%]*(?<value>[^&%']+)['%]*");
            if (column.QueryType != "range")
            {
                foreach (Match m in regex.Matches(query))
                {
                    string name = m.Groups["name"].Value;
                    string value = m.Groups["value"].Value;

                    if (name == column.Name)
                        return value;
                }
            }
            else
            {
                string result = string.Empty;
                foreach (Match m in regex.Matches(query))
                {
                    string name = m.Groups["name"].Value;
                    string value = m.Groups["value"].Value;

                    if (name == column.Name)
                    {
                        //处理只选择截止日期 没选择起始日期
                        if (string.IsNullOrEmpty(result) && m.ToString().IndexOf("<") > 0)
                            result += "|" + value + "|";
                        else
                            result += value + "|";
                    }


                }
                if (!string.IsNullOrEmpty(result))
                    result = result.Remove(result.Length - 1);
                return result;
            }
            return string.Empty;
        }

        IClsAliasManager aliasManager;
        IClsAliasManager IDataModelContext.AliasManager
        {
            get
            {
                return aliasManager;
            }
            set
            {
                aliasManager = value;
            }
        }
        /// <summary>
        /// 根据页面的表单信息，得到相应的数据库查询串
        /// </summary>
        /// <param name="modelName">模型名称</param>
        /// <param name="expr">表单信息，形如：address=sdfdf&name=sdfdf</param>
        /// <param name="isApprox">是否模糊匹配</param>
        /// <returns></returns>
        public string GetQueryCondition(string modelFileName, string expr, bool isApprox)
        {
            string query = string.Empty;
            //%24是$的转义字符
            Regex regex = new Regex(@"(?<name>[\w|\d]+)(%24(?<seq>\w+))*=(?<value>[^&,]+)");
            DataModel model = new DataModel(this, modelFileName);
            //用模版中的 DataModel name 而不是用URL中的Model 值

            string tableName = string.IsNullOrEmpty(model.physicalName) ? model.Name : model.physicalName;
            foreach (Match m in regex.Matches(expr))
            {
                string name = m.Groups["name"].Value;
                string seq = m.Groups["seq"].Value;
                string value = HttpUtility.UrlDecode(m.Groups["value"].Value);

                if (model.Columns.ContainsKey(name) && !string.IsNullOrEmpty(value))
                {
                    if (!string.IsNullOrEmpty(query))
                        query += " and ";
                    Type colType = model.Columns[name].ColumnType;
                    string queryType = model.Columns[name].QueryType;
                    if (queryType != "range")
                    {
                        if (isApprox)
                        {
                            if (colType == typeof(string) || colType == typeof(DateTime))
                                query += string.Format("{0}.{1} like '%{2}%'", tableName, name, value.Trim());
                            else
                                query += string.Format("{0}.{1}='{2}'", tableName, name, value.Trim());
                        }
                        else
                        {
                            query += string.Format("{0}.{1}='{2}'", tableName, name, value.Trim());
                        }
                    }
                    else
                    {
                        string op = seq == "1" ? ">=" : "<=";
                        if (colType == typeof(string) || colType == typeof(DateTime))
                            query += string.Format("{0}.{1}{2}'{3}'", tableName, name, op, value.Trim());
                        else
                            query += string.Format("{0}.{1}{2}{3}", tableName, name, op, value.Trim());
                    }
                }
            }
            return query;
        }
        /// <summary>
        /// 从数据库中获取流水号
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="colTag"></param>
        /// <returns>如果返回值是0,说明查询异常</returns>
        public int GetSequenceNo(string tableName, string colTag)
        {
            int iRtn = 0;
            iRtn = dboperator.GetSequenceNo(tableName, colTag);   //如果返回值是0说明查询异常
            return iRtn;
        }
        /// <summary>
        /// 当前登录用户
        /// </summary>
        public SystemUser CurrentUser
        {
            get
            {
                return Runtime.CurrentUser;
            }
        }
        /// <summary>
        /// 当前数据模型
        /// </summary>
        public DataModel CurrentModel
        {
            get
            {
                string modelName = HttpContext.Current.Request.QueryString["model"];
                if (!string.IsNullOrEmpty(modelName))
                {
                    return new DataModel(this, modelName);
                }
                return null;
            }
        }
        /// <summary>
        /// 当前URL
        /// </summary>
        public string CurrentUrl
        {
            get
            {
                return HttpContext.Current.Request.RawUrl;
            }
        }
        /// <summary>
        /// 获取当前日期
        /// </summary>
        /// <returns></returns>
        public DateTime GetDate()
        {
            return DateTime.Now;
        }

        SequenceNoGenerator snGenerator = new SequenceNoGenerator();
        /// <summary>
        /// 为列产生系统号
        /// </summary>
        /// <returns></returns>
        public string GetSequenceNo(DataModelColumn column)
        {
            if (string.IsNullOrEmpty(column.SequenceNoGenType))
                throw new Common.Exception.WMSSysException("请配置流水号的生成方式");
            else
            {
                return snGenerator.Generate(column.SequenceNoGenType, column.Model.Name, column.Name, this).ToString();
            }
        }

        /// <summary>
        /// 转换表达式的值
        /// </summary>
        /// <param name="expr"></param>
        /// <returns></returns>
        public object Evaluate(string expr)
        {
            return CommandExprFactory.Eval(expr, this);
        }

    }
}
